import 'dart:async';
import 'dart:io';

import 'package:flutter_base/common/widgets/widgets.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_base/common/utils/utils.dart';
import 'package:flutter_base/common/values/values.dart';
import 'package:flutter/material.dart';
import 'package:keyboard_actions/keyboard_actions.dart';

Widget inputTextEdit({
  required TextEditingController controller,
  TextInputType keyboardType = TextInputType.text,
  String? hintText,
  bool isPassword = false,
  double marginTop = 15,
  Color bgColor = AppColors.secondaryElement,
}) {
  return Container(
    height: zhiSetHeight(44),
    margin: EdgeInsets.only(top: zhiSetHeight(marginTop)),
    decoration: BoxDecoration(
      color: bgColor,
      borderRadius: Radii.k6pxRadius,
    ),
    child: TextField(
      controller: controller,
      keyboardType: keyboardType,
      decoration: InputDecoration(
        hintText: hintText,
        contentPadding: EdgeInsets.fromLTRB(20, 10, 0, 9),
        border: InputBorder.none,
      ),
      style: TextStyle(
        color: AppColors.primaryText,
        fontFamily: "Avenir",
        fontWeight: FontWeight.w400,
        fontSize: zhiSetFontSize(18),
      ),
      maxLines: 1,
      autocorrect: false,
      // 自动纠正
      obscureText: isPassword, // 隐藏输入内容, 密码框
    ),
  );
}

/// email 输入框
/// 背景白色，文字黑色，带阴影
Widget inputEmailEdit({
  required TextEditingController controller,
  TextInputType keyboardType = TextInputType.text,
  String? hintText,
  bool isPassword = false,
  double marginTop = 15,
  bool autofocus = false,
  double? height,
  int? maxLines = 1,
}) {
  return Container(
    height: height,
    margin: EdgeInsets.only(top: zhiSetHeight(marginTop)),
    decoration: BoxDecoration(
      color: AppColors.primaryBackground,
      borderRadius: Radii.k6pxRadius,
      boxShadow: [
        // BoxShadow(
        //   color: Color.fromARGB(41, 0, 0, 0),
        //   offset: Offset(0, 1),
        //   blurRadius: 0,
        // ),
      ],
    ),
    child: TextField(
      autofocus: autofocus,
      controller: controller,
      keyboardType: keyboardType,
      decoration: InputDecoration(
        hintText: hintText,
        contentPadding: EdgeInsets.fromLTRB(20, 10, 0, 9),
        border: InputBorder.none,
        hintStyle: TextStyle(
          color: AppColors.thirdElementText,
        ),
      ),
      style: TextStyle(
        color: AppColors.primaryText,
        fontFamily: "Avenir",
        fontWeight: FontWeight.w400,
        fontSize: zhiSetFontSize(18),
      ),
      maxLines: maxLines,
      autocorrect: false,
      // 自动纠正
      obscureText: isPassword, // 隐藏输入内容, 密码框
    ),
  );
}

//键盘配置
KeyboardActionsConfig getKeyboardActionsConfig(
    BuildContext context, List<FocusNode> list) {
  return KeyboardActionsConfig(
    keyboardBarColor: Colors.grey[200],
    nextFocus: true,
    actions: List.generate(
        list.length,
        (i) => KeyboardActionsItem(
              focusNode: list[i],
              toolbarButtons: [
                (node) {
                  return GestureDetector(
                    onTap: () => node.unfocus(),
                    child: Padding(
                      padding: EdgeInsets.only(right: 16.0),
                      child: const Text('关闭'),
                    ),
                  );
                },
              ],
            )),
  );
}

class Input extends StatefulWidget {
  const Input(
      {Key? key,
      required this.controller,
      this.maxLength = 100,
      this.autoFocus = false,
      this.keyboardType = TextInputType.text,
      this.hintText = '',
      this.hintTextColor,
      this.focusNode,
      this.textAlign =TextAlign.start,
      this.enabled = true,
      this.canDelete = true,
      this.isInputPwd = false,
      this.getVCode,
      this.keyName,
      this.inputFormatters, this.onChanged})
      : super(key: key);

  final TextEditingController controller;
  final int maxLength;
  final bool autoFocus;
  final bool enabled;
  final bool canDelete;
  final TextInputType keyboardType;
  final List<TextInputFormatter>? inputFormatters;
  final String hintText;
  final Color? hintTextColor;
  final FocusNode? focusNode;
  final TextAlign? textAlign;
  final bool isInputPwd;
  final Future<bool> Function()? getVCode;
  final ValueChanged<String>? onChanged;

  /// 用于集成测试寻找widget
  final String? keyName;

  @override
  _InputState createState() => _InputState();
}

class _InputState extends State<Input> {
  bool _isShowPwd = false;
  bool _isShowDelete = false;
  bool _clickable = true;

  /// 倒计时秒数
  final int _second = 30;

  /// 当前秒数
  late int _currentSecond;
  StreamSubscription? _subscription;

  @override
  void initState() {
    /// 获取初始化值
    _isShowDelete = widget.controller.text.isNotEmpty;

    /// 监听输入改变
    widget.controller.addListener(isEmpty);
    super.initState();
  }

  void isEmpty() {
    final bool isNotEmpty = widget.controller.text.isNotEmpty;

    /// 状态不一样在刷新，避免重复不必要的setState
    if (isNotEmpty != _isShowDelete) {
      setState(() {
        _isShowDelete = isNotEmpty;
      });
    }
  }

  @override
  void dispose() {
    _subscription?.cancel();
    widget.controller.removeListener(isEmpty);
    super.dispose();
  }

  Future _getVCode() async {
    final bool isSuccess = await widget.getVCode!();
    if (isSuccess) {
      setState(() {
        _currentSecond = _second;
        _clickable = false;
      });
      _subscription = Stream.periodic(const Duration(seconds: 1), (int i) => i)
          .take(_second)
          .listen((int i) {
        setState(() {
          _currentSecond = _second - i - 1;
          _clickable = _currentSecond < 1;
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final ThemeData themeData = Theme.of(context);
    final bool isDark = themeData.brightness == Brightness.dark;

    Widget textField = TextField(
      enabled: widget.enabled,
      focusNode: widget.focusNode,
      maxLength: widget.maxLength,
      maxLines: 1,
      obscureText: widget.isInputPwd && !_isShowPwd,
      autofocus: widget.autoFocus,
      controller: widget.controller,
      textInputAction: TextInputAction.done,
      textAlign: widget.textAlign!=null?widget.textAlign!:TextAlign.start,
      keyboardType: widget.keyboardType,
      style: TextStyle(color: widget.hintTextColor),
      // 数字、手机号限制格式为0到9， 密码限制不包含汉字
      inputFormatters: widget.inputFormatters != null
          ? widget.inputFormatters
          : (widget.keyboardType == TextInputType.number ||
                  widget.keyboardType == TextInputType.phone)
              ? [FilteringTextInputFormatter.allow(RegExp('[0-9]'))]
              // : [FilteringTextInputFormatter.deny(RegExp('[\u4e00-\u9fa5]'))],
              : [],
      onChanged: (val) {
        if(widget.onChanged!=null){
          widget.onChanged!(val);
        }
      },
      decoration: InputDecoration(
        contentPadding:  EdgeInsets.symmetric(vertical: zhiSetHeight(11)),
        hintText: widget.hintText,
        hintStyle: TextStyle(color: widget.hintTextColor),
        counterText: '',
        border: InputBorder.none,
        // focusedBorder: UnderlineInputBorder(
        //   borderSide: BorderSide(
        //     color: themeData.primaryColor,
        //     width: 0,
        //   ),
        // ),
        // enabledBorder: UnderlineInputBorder(
        //   borderSide: BorderSide(
        //     color: Color(0xffd3d7d4),
        //     width: 0,
        //   ),
        // ),
      ),
    );

    /// 个别Android机型（华为、vivo）的密码安全键盘不弹出问题（已知小米正常），临时修复方法：https://github.com/flutter/flutter/issues/68571 (issues/61446)
    /// 怀疑是安全键盘与三方输入法之间的切换冲突问题。
    if (Platform.isAndroid) {
      textField = Listener(
        onPointerDown: (e) =>
            FocusScope.of(context).requestFocus(widget.focusNode),
        child: textField,
      );
    }

    Widget? clearButton;

    if (_isShowDelete&&widget.canDelete) {
      clearButton = Semantics(
        label: '清空',
        hint: '清空输入框',
        child: GestureDetector(
          child: loadAssetImage(
            'login/qyg_shop_icon_delete',
            width: 18.0,
            height: 40.0,
          ),
          onTap: () => widget.controller.text = '',
        ),
      );
    }

    late Widget pwdVisible;
    if (widget.isInputPwd) {
      pwdVisible = Semantics(
        label: '密码可见开关',
        hint: '密码是否可见',
        child: GestureDetector(
          child: loadAssetImage(
            _isShowPwd
                ? 'login/qyg_shop_icon_display'
                : 'login/qyg_shop_icon_hide',
            width: 18.0,
            height: 40.0,
          ),
          onTap: () {
            setState(() {
              _isShowPwd = !_isShowPwd;
            });
          },
        ),
      );
    }

    late Widget getVCodeButton;

    return Stack(
      alignment: Alignment.centerRight,
      children: <Widget>[
        textField,
        Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            /// _isShowDelete参数动态变化，为了不破坏树结构使用Visibility，false时放一个空Widget。
            /// 对于其他参数，为初始配置参数，基本可以确定树结构，就不做空Widget处理。
            Visibility(
              visible: _isShowDelete&&widget.canDelete,
              child: clearButton ?? SizedBox(width: zhiSetWidth(0)),
            ),
            if (widget.isInputPwd) SizedBox(width: zhiSetWidth(15)),
            if (widget.isInputPwd) pwdVisible,
          ],
        )
      ],
    );
  }
}
